import React, { useEffect, useState } from 'react';
import './index.less';
import { JumboTabs, NavBar, Empty, Dialog, Toast } from 'antd-mobile';
import { history, request } from 'umi';
import Climited from './climited';

export default function Climit() {
  const [dataList, setdatalist] = useState([]);
  const [key, setkey] = useState(history.location.state);
  const [token, setToken] = useState(sessionStorage.getItem('token') || '');
  useEffect(() => {
    goodShow(key);
  }, []);
  function back() {
    history.goBack();
  }
  async function goodShow(keys) {
    console.log(keys, 35);
    if (keys == undefined) {
      keys = 1;
    } else {
      setkey(keys);
    }
    let data = await request('/api/limite/good/' + keys, { method: 'POST' });
    console.log(data, '分类数据1');
    if (data.code == 200) {
      console.log(data, '分类数据2');

      setdatalist(data.data);
    }
  }
  async function setDone(id) {
    if (token) {
      console.log(id, '父组件接受');
      let data = await request('/api/coupons/done/' + id, { method: 'POST' });
      if (data.code == 200) {
        goodShow(key);
      }
    } else {
      Dialog.confirm({
        content: '请先登录',
        onConfirm: async () => {
          setTimeout(() => {
            history.push('/username');
          }, 3000);
          Toast.show({
            icon: 'loading',
            content: '加载中…',
          });
        },
      });
    }
  }
  return (
    <div className="climit">
      <NavBar onBack={back}>秒杀活动</NavBar>
      <JumboTabs
        defaultActiveKey={key}
        activeKey={key}
        onChange={(key) => goodShow(key)}
      >
        {dataList.map((item, index) => {
          return (
            <JumboTabs.Tab
              title={item.startTime.slice(11, 16)}
              description={item.done ? '进行中' : '即将开始'}
              key={item._id}
            >
              {dataList.length != 0 ? (
                <Climited {...item} key={item._id} setDone={setDone}></Climited>
              ) : (
                <Empty description="暂无秒杀商品" />
              )}
            </JumboTabs.Tab>
          );
        })}
      </JumboTabs>
    </div>
  );
}
